//
//  PZLViewController.m
//  Various
//
//  Created by dllo on 16/3/26.
//  Copyright © 2016年 Harword. All rights reserved.
//

#import "PZLViewController.h"
#import "PZLTableViewCell.h"
#import "HLNetWorkTool.h"
#import "PZLColumnsModel.h"
#import "PZLItemsModel.h"
#import "SDCycleScrollView.h"
#import "PZLPromotionModel.h"
#import "PZLDisplayModel.h"
#import "PZLHTMLViewController.h"
#import "PZLYiweiViewController.h"
#import "PZLLocationViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface PZLViewController ()<UITableViewDataSource, UITableViewDelegate, SDCycleScrollViewDelegate, PZLLocationViewControllerDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *modelArr;
@property (nonatomic, strong)NSMutableArray *titleArr;
@property (nonatomic, strong)NSMutableArray *dicArr;
@property (nonatomic, strong)NSDictionary *dicInfo; //上拉加载
@property (nonatomic, strong)NSMutableArray *promotionArr;//轮播图数组
@property (nonatomic, strong)NSMutableArray *displayArr;//一味和摄影札记数组
@property (nonatomic, strong)UILabel *label;

@property (nonatomic, strong)CLLocationManager *locationManager;

@end

@implementation PZLViewController



- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatSubView];
    [self creatMjRefresh];
    [self creatLocation];
    
}


- (void)creatMjRefresh{
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(creatJson)];
    [self.tableView.mj_header beginRefreshing];
    
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(creatFoot)];
    [self.tableView reloadData];

    
    
}



- (void)creatJson{
   
    [HLNetWorkTool getWithURL:@"http://wl.myzaker.com/?_appid=AndroidPhone&_v=6.5&_version=6.52&c=columns&city=dalian" Parameter:nil HttpHeader:nil ResponseType:ResponseTypeJSON Progress:^(NSProgress *progress) {
        
        
    } Success:^(id result) {
        
        self.titleArr = [NSMutableArray array];
        self.dicArr = [NSMutableArray array];
        self.dicInfo = [NSDictionary dictionary];
        self.promotionArr = [NSMutableArray array];// 轮播图数组
        self.displayArr = [NSMutableArray array]; //一味摄影札记数组
        
        NSDictionary *dic = [result objectForKey:@"data"];
        self.dicInfo = [dic objectForKey:@"info"];// 下拉刷新
        
        // 轮播图
        NSArray *promoteArr = [dic objectForKey:@"promote"];
        for (NSDictionary *promote in promoteArr) {
            PZLPromotionModel *model = [PZLPromotionModel baseModelWithDict:promote];
            [self.promotionArr addObject:model];
        }
        
    
        // 一味和摄影札记
        NSArray *displayArr = [dic objectForKey:@"display"];
        for (NSDictionary *display in displayArr) {
            PZLDisplayModel *model = [PZLDisplayModel baseModelWithDict:display];
            [self.displayArr addObject:model];
        }
        
        
        NSArray *array = [dic objectForKey:@"columns"];
        for (NSDictionary *temp in array) {
           PZLColumnsModel *model = [PZLColumnsModel baseModelWithDict:temp];
            
             self.modelArr = [NSMutableArray array];
            for (NSDictionary *dict in model.items) {
                PZLItemsModel *itemsModel = [PZLItemsModel baseModelWithDict:dict];
                [self.modelArr addObject:itemsModel];
            }

            [self.titleArr addObject:model.title];
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:self.modelArr forKey:model.title];
            [self.dicArr addObject:dict];
           
        }
        [self creatYiWeiSheYing];
        [self creatScrollView];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
        
    } Failure:^(NSError *error) {
        
        
    }];
}


// 一味摄影札记
- (void)creatYiWeiSheYing{
    
    PZLDisplayModel *modelYiWei = self.displayArr[0];
    PZLDisplayModel *modelSheYing = self.displayArr[1];
    
    // 一味
    UIImageView *imageViewYiWei = [[UIImageView alloc] initWithFrame:CGRectMake(4 * sWEIGHT, 216*sHEIGHT, (sWEIGHT * 414-12*sWEIGHT)/2, 80*sHEIGHT)];
    [imageViewYiWei sd_setImageWithURL:[NSURL URLWithString:[modelYiWei.pic objectForKey:@"url"]] placeholderImage:[UIImage imageNamed:@""]];
    imageViewYiWei.userInteractionEnabled = YES;
    
    // 手势点击
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickYiWei)];
    [imageViewYiWei addGestureRecognizer:tapRecognizer];
    
    [self.tableView.tableHeaderView addSubview:imageViewYiWei];
    
    
    // 摄影札记
    UIImageView *imageViewSheYing = [[UIImageView alloc] initWithFrame:CGRectMake((sWEIGHT * 414-12*sWEIGHT)/2 + 8*sWEIGHT, 216*sHEIGHT, (sWEIGHT * 414-12*sWEIGHT)/2, 80*sHEIGHT)];
    [imageViewSheYing sd_setImageWithURL:[NSURL URLWithString:[modelSheYing.pic objectForKey:@"url"]] placeholderImage:[UIImage imageNamed:@""]];
    
    imageViewSheYing.userInteractionEnabled = YES;
    // 手势点击
    UITapGestureRecognizer *tapRecogni = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickSheYing)];
    [imageViewSheYing addGestureRecognizer:tapRecogni];
    [self.tableView .tableHeaderView addSubview:imageViewSheYing];
    
    
    

}


// 点击事件
- (void)clickYiWei{
    PZLDisplayModel *model = self.displayArr[0];
    PZLYiweiViewController *tableVC = [[PZLYiweiViewController alloc]init];
    tableVC.url = [model.block_info objectForKey:@"api_url"];
    [self.navigationController pushViewController:tableVC animated:YES];
  
}


- (void)clickSheYing{
    PZLDisplayModel *model = self.displayArr[1];
    PZLYiweiViewController *tableVC = [[PZLYiweiViewController alloc]init];
    tableVC.url = [model.block_info objectForKey:@"api_url"];
    [self.navigationController pushViewController:tableVC animated:YES];
    

}



- (void)creatFoot{
    
    [HLNetWorkTool getWithURL:[self.dicInfo objectForKey:@"next_url"]  Parameter:nil HttpHeader:nil ResponseType:ResponseTypeJSON Progress:^(NSProgress *progress) {
        
        
    } Success:^(id result) {
        NSDictionary *dic = [result objectForKey:@"data"];
        NSArray *array = [dic objectForKey:@"columns"];
        self.dicInfo = [NSDictionary dictionary];
        self.dicInfo = [dic objectForKey:@"info"];
        for (NSDictionary *temp in array) {
            PZLColumnsModel *model = [PZLColumnsModel baseModelWithDict:temp];
            self.modelArr = [NSMutableArray array];
            for (NSDictionary *dict in model.items) {
                PZLItemsModel *itemsModel = [PZLItemsModel baseModelWithDict:dict];
                [self.modelArr addObject:itemsModel];
            }
            
            [self.titleArr addObject:model.title];
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:self.modelArr forKey:model.title];
            [self.dicArr addObject:dict];
            
        }
        
        [self.tableView reloadData];
        
         [self.tableView.mj_footer endRefreshing];
        
    } Failure:^(NSError *error) {
        
        
    }];

}


// 轮播图
- (void)creatScrollView{
    
    NSMutableArray *stringUrlArr = [NSMutableArray array];
    for (PZLPromotionModel *model in self.promotionArr) {
        if (model.article) {
            [stringUrlArr addObject:model.promotion_img];
        }
     
    }
    
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, sWEIGHT*414, 212*sHEIGHT) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
//    cycleScrollView.titlesGroup = titles;
    cycleScrollView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    [self.tableView.tableHeaderView addSubview:cycleScrollView];
    
    //         --- 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cycleScrollView.imageURLStringsGroup = stringUrlArr;
    });

}

// 轮播图点击方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    PZLHTMLViewController *htmlVC = [PZLHTMLViewController new];
    
    NSMutableArray *modelArray = [NSMutableArray array];
    for (PZLPromotionModel *model in self.promotionArr) {
        if (model.article) {
            [modelArray addObject:model];
        }
        
    }
    
    PZLPromotionModel *model = modelArray[index];
//    NSLog(@"%@", model.promotion_img);
    NSDictionary *dicInfo = [model.article objectForKey:@"special_info"];
    NSString *weburl = [dicInfo objectForKey:@"web_url"];
    htmlVC.web_url =  [NSString stringWithFormat:@"%@&target=web3&_version=6.52",weburl];
//    NSLog(@"-----%@", htmlVC.web_url);
    
    
    [self.navigationController pushViewController:htmlVC animated:YES];
}






- (void)creatSubView{
    
    // 定位城市选择
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200*sWEIGHT, 30*sHEIGHT)];
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160*sWEIGHT, 30*sHEIGHT)];
    [view addSubview:view1];
    
    self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 120*sWEIGHT, 20*sHEIGHT)];
    self.label.textAlignment = NSTextAlignmentRight;
    self.label.font = [UIFont systemFontOfSize:15*sWEIGHT];
    [view1 addSubview:self.label];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(130*sWEIGHT, 0, 30*sWEIGHT, 30*sHEIGHT)];
    imageView.image = [UIImage imageNamed:@"iconfont-dingwei"];
    [view1 addSubview:imageView];
    
    
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = rightBarButton;


    // 给view添加手势
    UITapGestureRecognizer *tapges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToLocation)];
    [view1 addGestureRecognizer:tapges];
    
    
    
    
    
    
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, sWEIGHT*414, sHEIGHT*736 - 113*sHEIGHT) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.rowHeight = 229*sHEIGHT;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, sWEIGHT * 414, 300*sHEIGHT)];
    
    [self.view addSubview:self.tableView];
    
}

- (void)goToLocation{
    PZLLocationViewController *locationVC = [[PZLLocationViewController alloc] init];
    locationVC.delegate = self;
    [self.navigationController pushViewController:locationVC animated:YES];
}







- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    NSLog(@"--%lu", (unsigned long)self.dicArr.count);
    return self.dicArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSMutableDictionary *dic = self.dicArr[section];
    NSArray *arr = [dic objectForKey:self.titleArr[section]];
//    NSLog(@"%lu", (unsigned long)arr.count);
    return  arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"text";
    PZLTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[PZLTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    NSDictionary *dic = self.dicArr[indexPath.section];
    NSArray *arrModel = [dic objectForKey:self.titleArr[indexPath.section]];
    
    PZLItemsModel *model = arrModel[indexPath.row];
    cell.model = model;
    return cell;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    return self.titleArr[section];
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic = self.dicArr[indexPath.section];
    NSArray *arrModel = [dic objectForKey:self.titleArr[indexPath.section]];
    
    PZLItemsModel *model = arrModel[indexPath.row];
    
    PZLHTMLViewController *htmlVC = [[PZLHTMLViewController alloc]init];
    htmlVC.full_url = [model.article objectForKey:@"full_url"];
    htmlVC.title = [model.article objectForKey:@"title"];
    htmlVC.auther = [model.article objectForKey:@"auther_name"];
    
//    htmlVC.navigationItem.hidesBackButton = YES;
    
//    NSLog(@"%@", [model.article objectForKey:@"title"]);
    [self.navigationController pushViewController:htmlVC animated:YES];
    
}



- (void)text:(PZLLocationModel *)model{
    self.label.text = model.city_name;
}




// 定位

- (void)creatLocation{
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    
    [self.locationManager startUpdatingLocation];
    
    
}



- (void)requestWhenInUseAuthorization
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    // If the status is denied or only granted for when in use, display an alert
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
        NSString *title;
        title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled";
        NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];
        [alertView show];
    }
    // The user has not enabled any location services. Request background authorization.
    else if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestAlwaysAuthorization];
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        // Send the user to the Settings for this app
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL];
    }
}



// 协议方法
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"经度=%f 纬度=%f 高度=%f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude, currentLocation.altitude);
    
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    // 根据经纬度方向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            // 将获得的所有信息显示到label上
            NSLog(@"-----%@", placemark.name);
            // 获取详细地址
//            self.detailLabel.text = placemark.name;
            //获取城市
            NSString *city = placemark.locality;
            // 获取区
//            self.countryLabel.text = placemark.subLocality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
                NSLog(@"%@", city);
            }
            self.label.text = city;
           
            NSLog(@"--%@", city);
        }else if (error == nil && placemarks.count == 0){
            NSLog(@"No results were returned");
        }else if (error != nil){
            NSLog(@"An error occurred = %@", error);
        }
        
        
    }];
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (error.code == kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
        NSLog(@"%@", error);
    }
}












- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
